﻿using System.Configuration;
using System.Web;
using CVsharp.MVClib.Cache;
using CVsharp.WebLib.Cache;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

namespace CVsharp.MVClib.ICO.Unity
{
    public static class ContainerFactory
    {
        public static IUnityContainer GetContainer()
        {

            if (HttpContext.Current.Application["container"] == null)
            {
                IUnityContainer Container = new UnityContainer();
                Container.RegisterType<IWebMemory, WebMemory>();//注册缓存

                // 基础数据维护的依赖注入配置
                LoadUnityConfigFile(Container, HttpContext.Current.Server.MapPath("~/unity.di.infrastructure.config"));
                // 基础数据维护的AOP配置
                //LoadUnityConfigFile(Container, HttpContext.Current.Server.MapPath("~/unity.aop.infrastructure.config"));
                HttpContext.Current.Application.Add("container", Container);
            }
            return (IUnityContainer)HttpContext.Current.Application["container"];
        }

        private static void LoadUnityConfigFile(IUnityContainer container, string exeConfigFilename)
        {
            ExeConfigurationFileMap infraFileMap = new ExeConfigurationFileMap
            {
                ExeConfigFilename = exeConfigFilename
            };
            UnityConfigurationSection infraConfig = (UnityConfigurationSection)ConfigurationManager
                .OpenMappedExeConfiguration(infraFileMap, ConfigurationUserLevel.None)
                .GetSection("unity");
            if (infraConfig.Containers.Default != null)
            {
                //
                //infraConfig.Containers.Default.Configure(container);
                //已过时，用下面的替换

                infraConfig.Configure(container);
            }
        }
    }
}
